package com.group3.controller;

import brave.Span;
import brave.Tracer;
import com.alibaba.fastjson2.JSON;
import com.group3.model.LoginRequest;
import com.group3.model.RegisterRequest;
import com.group3.model.User;
import com.group3.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/user") // 修改基础路径，便于扩展
@Slf4j
@CrossOrigin(origins = "http://localhost:63342", allowCredentials = "true")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @Autowired
    private Tracer tracer;

    // 原有查询接口保持不变
    @GetMapping("/{uid}")
    public User queryUserById(@PathVariable Integer uid) throws InterruptedException {
        // 原有查询逻辑保持不变
        Span currentSpan = tracer.currentSpan();
        log.info("查询用户信息, UID: {}, TraceID: {}, SpanID: {}",
                uid, currentSpan.context().traceIdString(), currentSpan.context().spanIdString());

        if (uid == 1) {
            log.info("模拟慢速查询，UID: {}", uid);
            Thread.sleep(60);
        }

        if (uid == 2) {
            log.error("查询用户信息失败，UID: {}", uid);
            throw new RuntimeException("查询用户信息失败");
        }

        User user = userService.queryUserById(uid);
        log.info("查询用户信息成功，UID: {}, 用户信息: {}", uid, JSON.toJSONString(user));
        rocketMQTemplate.sendOneWay("user-welcome", user);
        return user;
    }

    // 新增登录接口
    @PostMapping("/login")
    public ResponseEntity<?> login(@RequestBody LoginRequest request) {
        Span currentSpan = tracer.currentSpan();
        log.info("用户登录请求, 用户名: {}, TraceID: {}, SpanID: {}",
                request.getUsername(),
                currentSpan.context().traceIdString(),
                currentSpan.context().spanIdString());

        try {
            // 调用服务层验证用户（需在UserService中新增login方法）
            User user = userService.login(request.getUsername(), request.getPassword());

            // 登录成功，返回用户信息（实际项目中应返回Token）
            log.info("用户登录成功, 用户ID: {}, TraceID: {}",
                    user.getUid(),
                    currentSpan.context().traceIdString());
            return ResponseEntity.ok(user);

        } catch (IllegalArgumentException e) {
            // 登录失败，返回401状态码
            log.warn("用户登录失败: {}", e.getMessage());
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(e.getMessage());
        }
    }


    // 新增注册接口
    @PostMapping("/register")
    public User registerUser(@RequestBody RegisterRequest request) {
        // 获取当前Span并记录信息
        Span currentSpan = tracer.currentSpan();
        log.info("用户注册请求, 用户名: {}, TraceID: {}, SpanID: {}",
                request.getUsername(), currentSpan.context().traceIdString(), currentSpan.context().spanIdString());

        // 调用服务层注册方法
        User newUser = userService.registerUser(request);

        log.info("用户注册成功, 用户ID: {}, TraceID: {}",
                newUser.getUid(), currentSpan.context().traceIdString());

        return newUser;
    }

    @RequestMapping("/recommend/{uid}")
    public User queryRecommendProduct(@PathVariable Integer uid) {
        User user = userService.queryUserById(uid);
        log.info("请稍等，为您推荐商品中...");
        rocketMQTemplate.syncSend("user-recommend", user);
        return user;
    }
}